package top.eggcode.common.model;

import lombok.Data;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import java.io.Serializable;

/**
 * 分页
 *
 * @author jiaqi.ding
 */
@ToString(callSuper = true)
@Accessors(chain = true)
@Data
public class Pagination implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 页大小
     */
    private Integer size;

    /**
     * 页码
     */
    private Integer number;

    /**
     * 总记录数
     */
    private Integer total;

    /**
     * 排序字段
     */
    private String field;

    /**
     * 排序字段名
     */
    private String sortField;

    private String sortRule;

    {
        sortField = "root.created_at";
        sortRule = "dsc";
    }

    public Pageable convert() {
        Sort sort = null;
        if (StringUtils.isNotBlank(sortRule) && "dsc".equals(sortRule)) {
            sort = Sort.by(sortField).descending();
        } else {
            sort = Sort.by(sortField).ascending();
        }

        return PageRequest.of(this.getNumber() - 1, this.getSize(), sort);
    }
}
